﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class 采购退货管理 : Form
    {
        private readonly ISupplyReturnInfoRepository SupplyReturnInfo = new SupplyReturnInfoRepository();
        private readonly ISupplyOrderRepository SupplyOrder = new SupplyOrderRepository();

        private readonly ISupplyReturnOrderRepository SupplyReturnOrder = new SupplyReturnOrderRepository();
        //private readonly ISysSupplierRepository supplierRepository = new SysSupplierRepository();
        ///单据状态： 制单  已保存

        public 采购退货管理()
        {
            InitializeComponent();
        }

        #region 窗体绘制

        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #endregion 窗体绘制

        private string userId;
        private string userName;

        public 采购退货管理(string userId, string userName)
        {
            InitializeComponent();
            this.userId = userId;
            this.userName = userName;
        }

        #region 取消按钮，默认退出

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion 取消按钮，默认退出

        #region 新增按钮，跳转页面。初始化 订单编号与订单状态

        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripAdd_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 1;
            if (dataGridView1.Rows.Count > 0)
            {
                DialogResult RSS = MessageBox.Show(this, "请确保当前订单已经保存成功？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (RSS == DialogResult.Yes)
                {
                    dataGridView1.Rows.Clear();
                }
                else
                {
                    return;
                }
            }
            lab_djbh.Text = "";
            lab_ddzt.Text = "制单";
            toolStripLabel2.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            toolStripLabel4.Text = "";
            lab_thbm.Text = "";
            LAB_id.Text = "";
            lab_xszdID.Text = "";
            lab_thbm.Select();
        }

        #endregion 新增按钮，跳转页面。初始化 订单编号与订单状态

        #region Load

        private void 采购入库管理_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            lab_djbh.Text = "";
            lab_ddzt.Text = "";
            toolStripLabel3.Text = userName;
            Lab_HJcount.Text = "";
            toolStrip1.Text = "";
            toolStripLabel3.Text = "";
            //toolStripLabel4.Text = "";
            LAB_id.Text = "";
            lab_thbm.Text = "";
            this.toolStripLabel4.Margin = new System.Windows.Forms.Padding(this.Width - 700, 1, 0, 2);
            BingOrder();
        }

        #endregion Load

        #region 绑定退货订单

        /// <summary>
        /// 绑定退货订单
        /// </summary>
        private void BingOrder()
        {
            dgvSupplyList.AutoGenerateColumns = false;
            var SalesRrturnOrderModel = SupplyReturnOrder.GetSupplyReturnList();
            dgvSupplyList.Rows.Clear();
            for (int i = 0; i < SalesRrturnOrderModel.ToList().Count; i++)
            {
                dgvSupplyList.Rows.Add();
                dgvSupplyList.Rows[i].Cells["退货订单编号"].Value = SalesRrturnOrderModel.ToList()[i].OrderCode;
                dgvSupplyList.Rows[i].Cells["制单人"].Value = SalesRrturnOrderModel.ToList()[i].CreateUserName;
                dgvSupplyList.Rows[i].Cells["制单时间"].Value = SalesRrturnOrderModel.ToList()[i].CreateTime;
                dgvSupplyList.Rows[i].Cells["退货订单状态"].Value = SalesRrturnOrderModel.ToList()[i].State;
                dgvSupplyList.Rows[i].Cells["退货入库时间"].Value = SalesRrturnOrderModel.ToList()[i].PutTime;
                dgvSupplyList.Rows[i].Cells["Id"].Value = SalesRrturnOrderModel.ToList()[i].Id;
            }
            for (int i = 0; i < dgvSupplyList.Rows.Count; i++)
            {
                //绑定订单状态
                if (dgvSupplyList.Rows[i].Cells["退货订单状态"].Value.ToString() == "0")
                {
                    dgvSupplyList.Rows[i].Cells["退货订单状态"].Value = "已保存";
                    dgvSupplyList.Rows[i].DefaultCellStyle.BackColor = Color.GreenYellow;
                }
                if (dgvSupplyList.Rows[i].Cells["退货订单状态"].Value.ToString() == "1")
                {
                    dgvSupplyList.Rows[i].Cells["退货订单状态"].Value = "已完成";
                    dgvSupplyList.Rows[i].DefaultCellStyle.BackColor = Color.Gray;
                }
                dgvSupplyList.ClearSelection();
            }
        }

        #endregion 绑定退货订单

        #region 绘制订单序号，并且统计总数量与总金额

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            double Money = 0.00;
            double Count = 0;
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
          e.RowBounds.Location.Y,
          dataGridView1.RowHeadersWidth - 4,
          e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   dataGridView1.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            try
            {
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells["金额"].Value != null)
                    {
                        Count++;
                        double num = double.Parse(dataGridView1.Rows[i].Cells["金额"].Value.ToString().Replace("￥", ""));
                        Money += num;
                    }
                }
                Lab_HJcount.Text = "合计：" + Count.ToString() + "笔 ";
                toolStripLabel2.Text = "总金额:￥" + Money.ToString();
            }
            catch (Exception ex)
            {
            }
        }

        #endregion 绘制订单序号，并且统计总数量与总金额

        #region 绑定采购订单明细

        private void dgvSupplyList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = dgvSupplyList.CurrentCell.RowIndex;
                string Id = dgvSupplyList.Rows[index].Cells["Id"].Value.ToString();
                lab_thbm.Text = dgvSupplyList.Rows[index].Cells["退货订单编号"].Value.ToString();
                lab_ddzt.Text = dgvSupplyList.Rows[index].Cells["退货订单状态"].Value.ToString();
                lab_xszdID.Text = Id;
                toolStripLabel4.Text = $"制表时间：{dgvSupplyList.Rows[index].Cells["制单时间"].Value.ToString()}";
                var SupplyOderInfo = SupplyReturnOrder.GetSupplyReturnInfoList(int.Parse(Id));
                tabControl1.SelectedIndex = 1;
                dataGridView1.Rows.Clear();
                for (int i = 0; i < SupplyOderInfo.Count; i++)
                {
                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells["采购退货订单明细ID"].Value = SupplyOderInfo[i].Id;
                    dataGridView1.Rows[i].Cells["药品编码"].Value = SupplyOderInfo[i].ProductId;
                    dataGridView1.Rows[i].Cells["药品名称"].Value = SupplyOderInfo[i].ProductName;
                    dataGridView1.Rows[i].Cells["生产企业"].Value = SupplyOderInfo[i].ManufacturingEnterprise;
                    dataGridView1.Rows[i].Cells["进价"].Value = SupplyOderInfo[i].Price;
                    dataGridView1.Rows[i].Cells["数量"].Value = SupplyOderInfo[i].Quantity;
                    dataGridView1.Rows[i].Cells["金额"].Value = SupplyOderInfo[i].TotalMoney;
                    dataGridView1.Rows[i].Cells["药品批号"].Value = SupplyOderInfo[i].BatchNumber;
                    dataGridView1.Rows[i].Cells["药品有效期"].Value = SupplyOderInfo[i].DateExpiry;
                    dataGridView1.Rows[i].Cells["可退货数量"].Value = SupplyOderInfo[i].QuantityReturned;
                    dataGridView1.Rows[i].Cells["退货数量"].Value = SupplyOderInfo[i].Quantity;
                }
                this.dataGridView1.Refresh();
            }
            catch (Exception w)
            {
                //  }
            }
        }

        #endregion 绑定采购订单明细

        #region 解决切换卡顿重影

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int page = tabControl1.SelectedIndex;
            if (page == 0)
            {
                BingOrder();
            }
        }

        #endregion 解决切换卡顿重影

        #region 根据采购订单编号查询明细

        private void button1_Click(object sender, EventArgs e)
        {
            if (lab_djbh.Text.Length != 20)
            {
                MessageBox.Show("请仔细核对订单编号！");
                dataGridView1.Rows.Clear();
                return;
            }
            lab_ddzt.Text = "制表";
            string 采购单据编号 = lab_djbh.Text.Trim();
            int 采购订单ID;
            var SupplyOrderModel = SupplyOrder.GetList($" where  OrderCode='{采购单据编号}'", new { });
            if (SupplyOrderModel.Count() > 0)
            {
                采购订单ID = SupplyOrderModel.ToList()[0].Id;
                LAB_id.Text = 采购订单ID.ToString();
                var SupplyOderInfo = SupplyOrder.GetSupplyInfoReturnQuantityList(采购订单ID);
                dataGridView1.Rows.Clear();
                for (int i = 0; i < SupplyOderInfo.Count; i++)
                {
                    dataGridView1.Rows.Add();
                    dataGridView1.Rows[i].Cells["采购退货订单明细ID"].Value = SupplyOderInfo[i].Id;
                    dataGridView1.Rows[i].Cells["药品编码"].Value = SupplyOderInfo[i].ProductId;
                    dataGridView1.Rows[i].Cells["药品名称"].Value = SupplyOderInfo[i].ProductName;
                    dataGridView1.Rows[i].Cells["生产企业"].Value = SupplyOderInfo[i].ManufacturingEnterprise;
                    dataGridView1.Rows[i].Cells["进价"].Value = SupplyOderInfo[i].Price;
                    dataGridView1.Rows[i].Cells["数量"].Value = SupplyOderInfo[i].Quantity;
                    dataGridView1.Rows[i].Cells["金额"].Value = SupplyOderInfo[i].TotalMoney;
                    dataGridView1.Rows[i].Cells["药品批号"].Value = SupplyOderInfo[i].BatchNumber;
                    dataGridView1.Rows[i].Cells["药品有效期"].Value = SupplyOderInfo[i].DateExpiry;
                    dataGridView1.Rows[i].Cells["可退货数量"].Value = SupplyOderInfo[i].QuantityReturned;
                }
            }
            else
            {
                MessageBox.Show("查无此单!");
                return;
            }
        }

        #endregion 根据采购订单编号查询明细

        #region 部分退货

        private void 部分退货_Click(object sender, EventArgs e)
        {
            int index;
            decimal THcount = 0;
            try
            {
                if (lab_ddzt.Text == "已完成")
                {
                    MessageBox.Show("该订单已完成！不能修改");
                    return;
                }
                index = dataGridView1.CurrentCell.RowIndex;
            }
            catch (Exception)
            {
                return;
            }
            ToolStripMenuItem TSM = (ToolStripMenuItem)sender;
            if (TSM.Name == "全部退货")
            {
                THcount = decimal.Parse(dataGridView1.Rows[index].Cells["可退货数量"].Value.ToString());
            }
            else
            {
                退货数量填写 thsltx = new 退货数量填写();
                thsltx.ShowDialog();
                if (thsltx.DialogResult == DialogResult.OK)
                {
                    if (decimal.Parse(dataGridView1.Rows[index].Cells["可退货数量"].Value.ToString()) >= decimal.Parse(thsltx.Tag.ToString()))
                    {
                        THcount = decimal.Parse(thsltx.Tag.ToString());
                    }
                    else
                    {
                        MessageBox.Show("退货数量超出可退数量！");
                    }
                }
            }

            dataGridView1.Rows[index].Cells["退货数量"].Value = THcount.ToString();
        }

        #endregion 部分退货

        //保存/修改采购退货订单  (inert  与  update)
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count <= 0)
            {
                MessageBox.Show("无数据可保存");
                return;
            }
            if (lab_ddzt.Text == "已完成")
            {
                MessageBox.Show("此订单已完成,无法修改!");
                return;
            }
            SupplyReturnOrder order = new SupplyReturnOrder()
            {
                State = 0,
                CreateUserId = int.Parse(this.userId)
            };

            List<SupplyReturnInfo> SalesReturnList = new List<SupplyReturnInfo>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells["退货数量"].Value == null)
                {
                    continue;
                }
                var info = new SupplyReturnInfo();
                if (dataGridView1.Rows[i].Cells["药品批号"].Value != null)
                {
                    info.BatchNumber = dataGridView1.Rows[i].Cells["药品批号"].Value.ToString();
                }

                if (dataGridView1.Rows[i].Cells["药品有效期"].Value != null)
                {
                    info.DateExpiry = DateTime.Parse(dataGridView1.Rows[i].Cells["药品有效期"].Value.ToString());
                }

                info.OriginalSupplyInforId = dataGridView1.Rows[i].Cells["采购退货订单明细ID"].Value.ToString().ToInt();

                info.Price = decimal.Parse(dataGridView1.Rows[i].Cells["进价"].Value.ToString());
                info.ProductId = dataGridView1.Rows[i].Cells["药品编码"].Value.ToString().ToInt();
                info.Quantity = decimal.Parse(dataGridView1.Rows[i].Cells["退货数量"].Value.ToString());
                SalesReturnList.Add(info);
            }
            if (SalesReturnList.Count <= 0)
            {
                MessageBox.Show("无数据");
                return;
            }
            if (!lab_thbm.Text.IsNullOrEmpty()) //修改
            {
                order.Id = lab_xszdID.Text.ToInt();
                if (SupplyReturnOrder.UpdateSupplyReturn(order, SalesReturnList))
                {
                    MessageBox.Show("修改成功");
                }
                else
                {
                    MessageBox.Show("修改失败");
                }
            }
            else
            {
                order.SupplyOrderId = int.Parse(LAB_id.Text);
                int SalesReturnOrderId = SupplyReturnOrder.AddSupplyReturn(order, SalesReturnList);
                if (SalesReturnOrderId > 0)
                {
                    lab_xszdID.Text = SalesReturnOrderId.ToString();
                    var SalesReturnModel = SupplyReturnOrder.Get(SalesReturnOrderId);
                    {
                        // 读取退货单号与状态
                        lab_thbm.Text = SalesReturnModel.OrderCode.ToString();
                        if (SalesReturnModel.State == 0)
                        {
                            lab_ddzt.Text = "已保存";
                        }
                        else
                        {
                            lab_ddzt.Text = "已完成";
                        }
                        MessageBox.Show("保存成功");
                        var SalesReturnInfo = SupplyReturnOrder.GetSupplyReturnInfoList(SalesReturnOrderId);
                        dataGridView1.Rows.Clear();
                        for (int i = 0; i < SalesReturnInfo.Count; i++)
                        {
                            dataGridView1.Rows.Add();
                            dataGridView1.Rows[i].Cells["采购退货订单明细ID"].Value = SalesReturnInfo[i].OriginalSupplyInforId;
                            dataGridView1.Rows[i].Cells["药品编码"].Value = SalesReturnInfo[i].ProductId;
                            dataGridView1.Rows[i].Cells["药品名称"].Value = SalesReturnInfo[i].ProductName;
                            dataGridView1.Rows[i].Cells["生产企业"].Value = SalesReturnInfo[i].ManufacturingEnterprise;
                            dataGridView1.Rows[i].Cells["进价"].Value = SalesReturnInfo[i].Price;
                            dataGridView1.Rows[i].Cells["数量"].Value = SalesReturnInfo[i].Quantity;
                            dataGridView1.Rows[i].Cells["金额"].Value = SalesReturnInfo[i].TotalMoney;
                            dataGridView1.Rows[i].Cells["药品批号"].Value = SalesReturnInfo[i].BatchNumber;
                            dataGridView1.Rows[i].Cells["药品有效期"].Value = SalesReturnInfo[i].DateExpiry;
                            dataGridView1.Rows[i].Cells["可退货数量"].Value = SalesReturnInfo[i].QuantityReturned;
                            dataGridView1.Rows[i].Cells["退货数量"].Value = SalesReturnInfo[i].Quantity;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (lab_ddzt.Text.Contains("制单") || lab_ddzt.Text.Trim() == "")
            {
                MessageBox.Show("请先保存订单！确认无误后再入库！");
                return;
            }
            if (lab_ddzt.Text.Contains("已完成"))
            {
                MessageBox.Show("该订单已完成！");
                return;
            }
            int orderID = int.Parse(lab_xszdID.Text);
            if (SupplyReturnOrder.OutStore(orderID, int.Parse(this.userId)))
            {
                MessageBox.Show("商品退货出库成功！");
                var SalesReturnOrderMOdel = SupplyReturnOrder.Get(orderID);
                {
                    // 读取销售单号与状态
                    if (SalesReturnOrderMOdel.State == 0)
                    {
                        lab_ddzt.Text = "已保存";
                    }
                    else
                    {
                        lab_ddzt.Text = "已完成";
                    }
                    BingOrder();
                }
            }
        }
    }
}